from sqlalchemy.orm import Session
from typing import List, Optional, Dict, Any
from app.models.image import ImageRecord
from app.schemas.image import ImageCreate, ImageUpdate

class ImageCRUD:
    def create_image(self, db: Session, image_data: Dict[str, Any]) -> ImageRecord:
        """创建图片记录"""
        db_image = ImageRecord(**image_data)
        db.add(db_image)
        db.commit()
        db.refresh(db_image)
        return db_image
    
    def get_image_by_entity_id(self, db: Session, entity_id: str, group_id: str) -> Optional[ImageRecord]:
        """根据entity_id获取图片"""
        return db.query(ImageRecord).filter(
            ImageRecord.entity_id == entity_id,
            ImageRecord.group_id == group_id,
            ImageRecord.deleted_at.is_(None)
        ).first()
    
    def get_images_by_group(self, db: Session, group_id: str, skip: int = 0, limit: int = 100) -> List[ImageRecord]:
        """获取图库中的图片列表"""
        return db.query(ImageRecord).filter(
            ImageRecord.group_id == group_id,
            ImageRecord.deleted_at.is_(None)
        ).offset(skip).limit(limit).all()
    
    def delete_image(self, db: Session, entity_id: str, group_id: str) -> bool:
        """软删除图片"""
        image = self.get_image_by_entity_id(db, entity_id, group_id)
        if image:
            image.deleted_at = func.now()
            db.commit()
            return True
        return False
    
    # 在ImageCRUD类中添加以下方法
    def get_images_waterfall(self, db: Session, page: int = 1, page_size: int = 20, group_id: Optional[str] = None) -> tuple[List[ImageRecord], int]:
        """获取瀑布流图片数据"""
        query = db.query(ImageRecord).filter(ImageRecord.deleted_at.is_(None))
        
        # 如果指定了group_id，则过滤
        if group_id:
            query = query.filter(ImageRecord.group_id == group_id)
        
        # 按创建时间倒序排列
        query = query.order_by(ImageRecord.created_at.desc())
        
        # 获取总数
        total = query.count()
        
        # 分页
        offset = (page - 1) * page_size
        images = query.offset(offset).limit(page_size).all()
        
        return images, total

image_crud = ImageCRUD()
# 在现有导入中添加
from sqlalchemy.sql import func  # 如果还没有导入的话